package com.example.mq;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * RocketMqProducer
 *
 * 真实的 RocketMQ 生产者，通过 DefaultMQProducer 向指定主题发送消息。
 */
@Component
public class RocketMqProducer {
    private DefaultMQProducer producer;
    private final String producerGroup = "my-producer-group";
    private final String namesrvAddr = "localhost:9876";

    @PostConstruct
    public void start() throws Exception {
        producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(namesrvAddr);
        producer.start();
        System.out.println("RocketMqProducer 启动成功。");
    }

    /**
     * sendMessage：向指定主题发送消息
     * @param topic 主题名称
     * @param msg 消息内容
     */
    public SendResult sendMessage(String topic, String msg) throws Exception {
        Message message = new Message(topic, msg.getBytes("UTF-8"));
        SendResult sendResult = producer.send(message);
        System.out.println("RocketMqProducer sendMessage: " + sendResult);
        return sendResult;
    }

    @PreDestroy
    public void shutdown() {
        if (producer != null) {
            producer.shutdown();
        }
        System.out.println("RocketMqProducer 已关闭。");
    }
}